#include <avr/io.h>
#include <util/delay_basic.h>
#include "../usbtiny/def.h"
#include "icsp.h"

#define PGD_PIN			0
#define PGC_PIN			1

#define PIN_LOW(pin)	PORT_CLR(B, pin)
#define PIN_HIGH(pin)	PORT_SET(B, pin)

#define PIN_INPUT(pin)	DDR_CLR(B, pin)
#define PIN_OUTPUT(pin)	DDR_SET(B, pin)

#define set_PGC()		PIN_HIGH(PGC_PIN);
#define clr_PGC()		PIN_LOW(PGC_PIN);

#define set_PGD()		PIN_HIGH(PGD_PIN)
#define clr_PGD()		PIN_LOW(PGD_PIN)

#define GET_PGD()		(PINB & (1<<PGD_PIN))

#define PGD_input()		PIN_INPUT(PGD_PIN)
#define PGD_output()	PIN_OUTPUT(PGD_PIN)

void icsp_write(unsigned char data, unsigned char bit_len)
{
	unsigned char i, mask = 0x01;

	for(i=0; i<bit_len; i++) {
		if(mask & data) {
			set_PGD();
		} else {
			clr_PGD();
		}
		set_PGC();
		mask = mask << 1;
        clr_PGC();
	}
    clr_PGD();
}

unsigned char icsp_read(void)
{
	unsigned char mask = 0x01, read = 0;

	PGD_input();
	do {
		set_PGC();
		asm volatile("\tNOP");
		clr_PGC();
		if(GET_PGD()) {
			read |= mask;
		}
		mask = mask << 1;
	} while(mask);
	PGD_output();

	return read;
}
